/*
 * All rights Reserved, Designed By DataDriver
 * Copyright:    DataDriver.Inc
 * Company:      Zhuo Wo Infomation Technology (ShangHai) CO.LTD
 */
package com.sun.unsafe;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * list集合在多线程下是不安全的
 */
public class ListUnsafe {

    public static void main(String[] args) {

        /**
         * ConcurrentModificationException 会报并发修改异常
         * 解决方法：
         * 1、使用Vertor集合;synchronized使用了Synchronized加锁处理，效率很低
         * 2、使用集合的方法: Collections.synchronizedList
         * 3、使用JUC下面的的CopyOnWriteArrayList进行读写复制
         */
       // List<String> list = new ArrayList<>();

        //List<String> list = new Vector<>();
        //List<String> list = Collections.synchronizedList(new ArrayList<>());

        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(list);
            },String.valueOf(i)).start();
        }

    }
}
